package com.hxzy.bbs.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;

import com.hxzy.jsp.connection.JNDIBBSConection;
import com.hxzy.jsp.entity.User;
import com.hxzy.jsp.session.ErrorCode;
import com.hxzy.jsp.utils.Hashs;
import com.mysql.jdbc.StringUtils;

public class LoginTest extends AppServlet{
	private static final long serialVersionUID = 1L;

	public LoginTest() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException{
		request.setCharacterEncoding("utf-8");
		String username = request.getParameter("username");
		String passwd = request.getParameter("passwd");
		String remeberMe = request.getParameter("remeber_me");

		if (StringUtils.isEmptyOrWhitespaceOnly(username)) {
			response.sendRedirect("./error?error=" + ErrorCode.FIELD_REQUIRE);
			return;
		}
		if (StringUtils.isEmptyOrWhitespaceOnly(passwd)) {
			response.sendRedirect("./error?error=" + ErrorCode.FIELD_REQUIRE);
			return;
		}

		Calendar c = Calendar.getInstance();

		User user = null;
		try {
			
			Configuration configuration = new Configuration().configure();
			SessionFactory factory = configuration.buildSessionFactory();
			Session session = factory.openSession();
//			String hql = "select passwd,salt,id,username,nickname from User where username =:username";
			String hql = "from User where username =:username";
			List<User> list=session.createQuery(hql).setParameter("username", username).list();
			/*if (list == null || list.isEmpty()) {
				// TODO: 登录失败
				
			}*/
			user = (User) list.get(0);
			for(int i=0;i<list.size();i++){
				String _passwd = user.getPasswd();
				String _salt = user.getSalt();
				if (!_passwd.equals(DigestUtils.sha1Hex((_salt + passwd).getBytes()))) {
					break;
				}
			}
//			for(Object[] object : list){
//				String _passwd = (String)object[0];
//				String _salt = (String)object[1];
//				if (!_passwd.equals(DigestUtils.sha1Hex((_salt + passwd).getBytes()))) {
//					break;
//				}
////				user = new User((long)object[2],(String)object[3], (String)object[4], null,
////						c.getTimeInMillis() / 1000, User.USER);
//				break;
//			}
			if (user == null) {
				response.sendRedirect("./error?error=" + ErrorCode.USER_LOGIN_FAILED); // 用户名或者密码错误
				return;
			}
			request.getSession().setAttribute("user", user);

			Transaction tx = session.beginTransaction();
			long now= (int) (c.getTimeInMillis() / 1000);
			int timeout = 2*60;
//			User user2 = (User) session.get(User.class, user.getId());
			user.setGmtLogin(now);
			user.setGmtModified(now);
			user.setIpLogin(request.getRemoteAddr());
			user.setStatus(0);
			if ("1".equals(remeberMe)) {
				String hash = DigestUtils.sha1Hex(Hashs.createSalt() + request.getRemoteAddr());
				Cookie cookie = new Cookie("h", hash);
				cookie.setMaxAge(timeout); // 盐值存储一天
				response.addCookie(cookie);
				user.setHash(hash);
				user.setGmtHashExpires( (now + timeout));
			} else {
				Cookie cookie = new Cookie("h", null);
				cookie.setMaxAge(0);
				response.addCookie(cookie);
				user.setHash("");
				user.setGmtHashExpires( 0);
			}
			session.update(user);
			tx.commit();
			
			// 记录登陆 ip，记录登陆时间
			/*long now = (int) (c.getTimeInMillis() / 1000);
			int rowIndex = 1;
			stmt.close();
			
			stmt = conn.prepareStatement(
					"update `stu_bbs`.`user` set ip_login = ?, gmt_login = ?, gmt_modified = ?, hash = ?, gmt_hash_expires = ? "
							+ " where id = ?");
			stmt.setString(rowIndex++, request.getRemoteAddr());
			stmt.setLong(rowIndex++, now);
			stmt.setLong(rowIndex++, now);

			// 更新登陆 hash，保存在 cookie 里
			if ("1".equals(remeberMe)) {
				int timeout = 2*60;
				String hash = DigestUtils.sha1Hex(Hashs.createSalt() + request.getRemoteAddr());

				Cookie cookie = new Cookie("h", hash);
				cookie.setMaxAge(timeout); // 盐值存储一天
				response.addCookie(cookie);

				stmt.setString(rowIndex++, hash);
				stmt.setLong(rowIndex++, (now + timeout));
			} else {
				Cookie cookie = new Cookie("h", null);
				cookie.setMaxAge(0);
				response.addCookie(cookie);

				stmt.setString(rowIndex++, "");
				stmt.setLong(rowIndex++, 0);
			}
			stmt.setLong(rowIndex++, user.getid());
			stmt.execute();
			stmt.close();*/
		}catch(Exception e){
			
		}

		response.sendRedirect("./index");
	}

}

